package com.bigShen.mybatis.official.typeHandler;

import com.bigShen.mybatis.official.enumType.CurrenyEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.*;

/**
 * @Author eddy.shen
 * @Date 2018/11/25 21:20
 **/
@MappedJdbcTypes(JdbcType.VARCHAR)
public class EnumCurrencyTypeHandler extends BaseTypeHandler<CurrenyEnum> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, CurrenyEnum parameter, JdbcType jdbcType) throws SQLException {

        String value = CurrenyEnum.CNY.getKey();
        if (CurrenyEnum.CNY.getKey().equals(parameter.getKey().trim())) {
            value = CurrenyEnum.CNY.getKey();
        } else if (CurrenyEnum.HK.getKey().equals(parameter.getKey().trim())) {
            value = CurrenyEnum.HK.getKey();
        } else if (CurrenyEnum.US.getKey().equals(parameter.getKey().trim())) {
            value = CurrenyEnum.US.getKey();
        }

        ps.setString(i, value);

    }

    @Override
    public CurrenyEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
        if (null != rs.getString(columnName)) {
            if (CurrenyEnum.CNY.getKey().equals(rs.getString(columnName).trim())) {
                return CurrenyEnum.CNY;
            }
            if (CurrenyEnum.HK.getKey().equals(rs.getString(columnName).trim())) {
                return CurrenyEnum.HK;
            }
            if (CurrenyEnum.US.getKey().equals(rs.getString(columnName).trim())) {
                return CurrenyEnum.US;
            }
        }
        return CurrenyEnum.CNY;
    }

    @Override
    public CurrenyEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        if (null != rs.getString(columnIndex)) {
            if (CurrenyEnum.CNY.getKey().equals(rs.getString(columnIndex))) {
                return CurrenyEnum.CNY;
            }
            if (CurrenyEnum.HK.getKey().equals(rs.getString(columnIndex))) {
                return CurrenyEnum.HK;
            }
            if (CurrenyEnum.US.getKey().equals(rs.getString(columnIndex))) {
                return CurrenyEnum.US;
            }
        }
        return CurrenyEnum.CNY;
    }

    @Override
    public CurrenyEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        if (null != cs.getString(columnIndex)) {
            if (CurrenyEnum.CNY.getKey().equals(cs.getString(columnIndex))) {
                return CurrenyEnum.CNY;
            }
            if (CurrenyEnum.HK.getKey().equals(cs.getString(columnIndex))) {
                return CurrenyEnum.HK;
            }
            if (CurrenyEnum.US.getKey().equals(cs.getString(columnIndex))) {
                return CurrenyEnum.US;
            }
        }
        return CurrenyEnum.CNY;
    }

}
